﻿using Consul;
using ELF.Core;
using Ocelot.Configuration;
using Ocelot.ServiceDiscovery.Providers;
using Ocelot.Values;

namespace ELF.Modules.Ocelot
{
    public class MyServiceDiscoveryProvider : IServiceDiscoveryProvider
    {
        private readonly IConsulClient _consulClient;
        private readonly IServiceProvider _serviceProvider;
        private readonly ServiceProviderConfiguration _config;
        private readonly DownstreamRoute _downstreamRoute;

        public MyServiceDiscoveryProvider(IServiceProvider serviceProvider, ServiceProviderConfiguration config, DownstreamRoute downstreamRoute)
        {
            _serviceProvider = serviceProvider;
            _config = config;
            _downstreamRoute = downstreamRoute;
            _consulClient = serviceProvider.GetRequiredService<IConsulClient>();
        }

        public async Task<List<Service>> GetAsync()
        {
            var services = new List<Service>();
            var consulServices = await _consulClient.Agent.Services();

            foreach (var service in consulServices.Response.Values)
            {
                if(_downstreamRoute.ServiceName != service.Service) { continue; }
                services.Add(new Service(
                    service.Service,
                    new ServiceHostAndPort(service.Address, service.Port),
                    service.ID,
                    "v1",
                    service.Tags
                ));
                ConsoleLog.Info($"Service {service.Service} found at {service.Address}:{service.Port}");
            }

            return services;
        }
    }
}
